<template>
  <el-row>
    <el-col :span="12" v-for="item in devices" :key="item">
      {{ item.deviceName }} :
      <el-switch
        v-model="item.deviceStatus"
        active-text="Open"
        inactive-text="Close"
        @click="change(item)"
    /></el-col>
  </el-row>
</template>

<script>
import axios from "axios";
import Qs from "qs";
export default {
  name: "controlDev",
  data() {
    return {
      devices: {},
    };
  },

  mounted() {
    this.onInit();
  },
  methods: {
    onInit() {
      let self = this;
      axios({
        method: "post",
        url: "https://3098l4z890.picp.vip/querydevice",
        responseType: "json",
      })
        .then(function (info) {
          if (info.data.success) {
            console.log("axios成功");
            self.devices = info.data.data;

            for (let obj of self.devices) {
              console.log(obj);
              if (
                "ONLINE" == obj.deviceStatus ||
                "UNACTIVE" == obj.deviceStatus ||
                "OFFLINE" == obj.deviceStatus
              ) {
                obj.deviceStatus = true;
              } else {
                obj.deviceStatus = false;
              }
            }
            console.log(self.devices);
          } else {
            console.log("axios失败");
            return false;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    change(obj) {
      let self = this;
      if (obj.deviceStatus) {
        axios({
          method: "post",
          url: "https://3098l4z890.picp.vip/startdevice",
          data: Qs.stringify({
            //需要通过Qs的stringify转成formdata的形式
            deviceName: obj.deviceName,
          }),
          responseType: "json",
        })
          .then(function (info) {
            if (info.data.success) {
              console.log("axios成功");

              console.log(self.devices);
            } else {
              console.log("axios失败");
              return false;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        axios({
          method: "post",
          url: "https://3098l4z890.picp.vip/closedevice",
          data: Qs.stringify({
            //需要通过Qs的stringify转成formdata的形式
            deviceName: obj.deviceName,
          }),
          responseType: "json",
        })
          .then(function (info) {
            if (info.data.success) {
              console.log("axios成功");

              console.log(self.devices);
            } else {
              console.log("axios失败");
              return false;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
  },
};
</script>
<style></style>
